import { AddUser, DeleteUser, getRoles, getUsers, putUser } from '@/services/ant-design-pro/api';
import { PlusOutlined } from '@ant-design/icons';
import type { ProColumns } from '@ant-design/pro-components';
import { ModalForm, ProFormSelect, ProFormText, ProTable } from '@ant-design/pro-components';
import { useIntl } from '@umijs/max';
import { App, Button, Popconfirm, Tag, Tooltip, Tree } from 'antd';
import lodash from 'lodash';
import { useRef, useState } from 'react';

type GithubIssueItem = {
  url: string;
  id: number;
  number: number;
  title: string;
  labels: {
    name: string;
    color: string;
  }[];
  state: string;
  comments: number;
  created_at: string;
  updated_at: string;
  closed_at?: string;
};

async function requestData(val: any) {
  const res = {
    data: [],
    total: 0,
  };
  const rq = await getUsers({ params: val });
  if (rq.code === 0) {
    res.data = rq.msg;
    // res.total = parseInt(rq.options.total)
    res.total = rq.options.total;
  }
  return Promise.resolve(res);
}

export default ({ transTab, searchName }: any) => {
  const [addOrEdit, setAddOrEdit] = useState('add');
  const [currentRow, setCurrentRow] = useState<any>();
  const [modalVisit, setModalVisit] = useState(false);
  const actionRef = useRef<any>();
  const intl = useIntl();

  const { message } = App.useApp();
  const columns: ProColumns<GithubIssueItem>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({
        id: 'component.username',
        defaultMessage: '用户名',
      }),
      dataIndex: 'username',
      copyable: true,
      ellipsis: true,
      initialValue: searchName,
      // tooltip: '标题过长会自动收缩',
    },
    {
      disable: true,
      title: intl.formatMessage({
        id: 'component.roleName',
        defaultMessage: '角色名',
      }),
      dataIndex: 'labels',
      search: false,
      ellipsis: true,
      render: (_, record: any) => {
        return (
          <>
            {record.character &&
              record.character.map((val: any, i: any) => {
                return (
                  <Tooltip
                    color="green"
                    key={i}
                    title={() => {
                      const res = (
                        <Tree
                          showLine
                          fieldNames={{
                            key: 'id',
                            title: 'name',
                          }}
                          onSelect={() => {}}
                          defaultExpandAll
                          treeData={val.permission}
                        />
                      );
                      return val.permission ? res : '该角色无权限！';
                    }}
                  >
                    <Tag
                      onClose={async () => {
                        const data = lodash.cloneDeep(record);
                        // 防止修改admin密码
                        data.password = '1234';
                        data.character = data.character.filter((item: any) => {
                          return item.id !== val.id;
                        });
                        const res: any = await putUser({ data });
                        if (res.code === 0) {
                          record.character = record.character.filter((item: any) => {
                            return item.id !== val.id;
                          });
                          message.success(res.msg);
                        } else {
                          message.info(res.msg);
                          actionRef.current?.reload();
                        }
                      }}
                      style={{ margin: '3px 3px', cursor: 'pointer' }}
                      closable
                      onClick={(e: any) => transTab('角色管理', e.target.outerText)}
                      color="green"
                    >
                      {val.name}
                    </Tag>
                  </Tooltip>
                );
              })}
          </>
        );
      },
    },
    {
      title: intl.formatMessage({
        id: 'component.numberOfLogins',
        defaultMessage: '登录次数',
      }),
      ellipsis: true,
      key: 'loginTimes',
      dataIndex: 'loginTimes',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({
        id: 'component.lastLoginTime',
        defaultMessage: '最后登录时间',
      }),
      key: 'lastLogin',
      dataIndex: 'lastLogin',
      valueType: 'dateTime',
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: 'Email',
      key: 'email',
      dataIndex: 'email',
      valueType: 'text',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: intl.formatMessage({
        id: 'app.settings.basic.phone',
        defaultMessage: '联系电话',
      }),
      key: 'phone',
      ellipsis: true,
      dataIndex: 'phone',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({
        id: 'pages.searchTable.titleOption',
        defaultMessage: '操作',
      }),
      valueType: 'option',
      ellipsis: true,
      key: 'option',
      render: (text, record: any) => [
        <Button
          onClick={() => {
            setAddOrEdit('edit');
            setCurrentRow(record);
            setModalVisit(true);
          }}
          key="edit"
          size="small"
          type="primary"
          ghost
        >
          {intl.formatMessage({
            id: 'component.edit',
            defaultMessage: '编辑',
          })}
        </Button>,
        <Popconfirm
          key="delete"
          title={intl.formatMessage({
            id: 'component.deleteUser',
            defaultMessage: '删除用户',
          })}
          // description={`是否删除（${record.username}）用户`}
          description={intl.formatMessage(
            {
              id: 'component.requireDeleteUser',
              defaultMessage: '是否删除（{name}）用户？',
            },
            { name: record.username },
          )}
          onConfirm={() => {
            DeleteUser({ data: { id: record.id } }).then((res: any) => {
              if (res.code === 0) {
                message.success(
                  intl.formatMessage({
                    id: 'component.deleteUserSuccess',
                    defaultMessage: '删除用户成功',
                  }),
                );
                actionRef.current?.reload();
              }
            });
          }}
          onCancel={() => {}}
          okText="Yes"
          cancelText="No"
        >
          <Button size="small" danger>
            {intl.formatMessage({
              id: 'component.delete',
              defaultMessage: '删除',
            })}
          </Button>
        </Popconfirm>,
      ],
    },
  ];
  const onReset = () => {
    actionRef.current.reset();
  };
  return (
    <>
      <ModalForm
        title={
          addOrEdit === 'add'
            ? intl.formatMessage({
                id: 'component.createUser',
                defaultMessage: '新建用户',
              })
            : intl.formatMessage({
                id: 'component.modifyUser',
                defaultMessage: '修改用户',
              })
        }
        open={modalVisit}
        autoFocusFirstInput
        modalProps={{
          destroyOnClose: true,
          onCancel: () => setModalVisit(false),
        }}
        width={400}
        onFinish={async (val: any) => {
          if (val.character) {
            val.character = val.character.map((item: any) => {
              return {
                id: item,
              };
            });
          }
          if (addOrEdit === 'add') {
            const res: any = await AddUser({ data: val });
            if (res.code === 0) {
              message.success(res.msg);
              actionRef.current?.reload();
            } else {
              message.info(res.msg);
            }
          } else {
            const res: any = await putUser({ data: { ...val, id: currentRow.id } });
            if (res.code === 0) {
              message.success(res.msg);
              actionRef.current?.reload();
            } else {
              message.info(res.msg);
            }
          }
          setModalVisit(false);
        }}
      >
        <ProFormText
          name="username"
          label={intl.formatMessage({
            id: 'component.username',
            defaultMessage: '用户名',
          })}
          placeholder={intl.formatMessage({
            id: 'pages.login.username.required',
            defaultMessage: '请输入用户名',
          })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'pages.login.username.required',
                defaultMessage: '请输入用户名',
              }),
            },
          ]}
          initialValue={currentRow && currentRow.username}
        />

        <ProFormText
          initialValue={'1234'}
          placeholder={intl.formatMessage({
            id: 'component.enterPassword',
            defaultMessage: '请输入密码',
          })}
          name="password"
          label={intl.formatMessage({
            id: 'app.settings.security.password',
            defaultMessage: '密码',
          })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'component.enterPassword',
                defaultMessage: '请输入密码',
              }),
            },
          ]}
        />
        <ProFormText
          initialValue={currentRow && currentRow.email}
          placeholder={intl.formatMessage({
            id: 'app.settings.basic.email-message',
            defaultMessage: '请输入您的邮箱',
          })}
          name="email"
          label="Email"
        />
        <ProFormText
          initialValue={currentRow && currentRow.phone}
          placeholder={intl.formatMessage({
            id: 'app.settings.basic.phone-message',
            defaultMessage: '请输入您的联系电话',
          })}
          name="phone"
          label={intl.formatMessage({
            id: 'app.settings.basic.phone',
            defaultMessage: '联系电话',
          })}
        />
        <ProFormSelect
          name="character"
          label={intl.formatMessage({
            id: 'component.roleName',
            defaultMessage: '角色名',
          })}
          fieldProps={{
            mode: 'multiple',
          }}
          placeholder={intl.formatMessage({
            id: 'component.enterRoleName',
            defaultMessage: '请输入角色名',
          })}
          initialValue={
            currentRow &&
            currentRow.character &&
            currentRow.character.map((item: any) => {
              return item.id;
            })
          }
          request={async () => {
            let res = [];
            const data = await getRoles({ params: { current: '1', pageSize: '999999999' } });
            if (data.code === 0) {
              res = data.msg.map((item: any) => {
                return {
                  label: item.name,
                  value: item.id,
                  key: item.id,
                };
              });
            }
            return Promise.resolve(res);
          }}
        />
      </ModalForm>
      <ProTable<GithubIssueItem>
        onReset={onReset}
        columns={columns}
        actionRef={actionRef}
        request={requestData}
        scroll={{
          x: true,
        }}
        editable={{
          type: 'multiple',
        }}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
          defaultValue: {
            option: { fixed: 'right', disable: true },
          },
          onChange() {},
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        pagination={{}}
        dateFormatter="string"
        headerTitle={intl.formatMessage({
          id: 'pages.admin.userManagement',
          defaultMessage: '用户管理',
        })}
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setAddOrEdit('add');
              setCurrentRow(null);
              setModalVisit(true);
            }}
            type="primary"
          >
            {intl.formatMessage({
              id: 'pages.searchTable.new',
              defaultMessage: '新建',
            })}
          </Button>,
        ]}
      />
    </>
  );
};
